<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'comSearch', 'quickSearch', 'delete']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('shop.order.order.quick Search Fields') })"
        >
            <!-- 导出按钮 -->
            <el-button
                v-blur
                class="table-header-operate"
                type="warning"
                style="margin-left: 12px"
                @click="baTable.table.extend!.showExportDialog = true"
                :disabled="baTable.table.data!.length <= 0"
            >
                <Icon color="#ffffff" name="fa fa-paper-plane" />
                <span class="table-header-operate-text">导出</span>
            </el-button>

            <!-- 自定义公共渲染 -->
            <template #orderStatusSearch>
                <StatusWithBadge v-if="showAllStatus" v-model="baTable.comSearch.form.status" field="status" :data="statusInfo" />
                <el-tag v-else :type="getStatusType(orderStatus)">{{ $t('shop.order.order.status ' + orderStatus) }}</el-tag>
            </template>
        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef">
            <template #order_no_info>
                <el-table-column :label="t('shop.order.order.order_no_info')" header-align="center" min-width="300">
                    <template #default="{ row }">
                        <div>{{ t('shop.order.order.order_no') }}: {{ row.order_no }}</div>
                        <div>{{ t('shop.order.order.out_trade_no') }}: {{ row.out_trade_no }}</div>
                    </template>
                </el-table-column>
            </template>
            <!-- 商品名称 -->
            <template #goods_name>
                <el-table-column :label="t('shop.order.order.goods_name')" align="left" header-align="center" min-width="240">
                    <template #default="{ row }">
                        <div v-for="(item, key) in row.detail" :key="key">
                            <el-tooltip :visible="item.visible" placement="top">
                                <template #content>
                                    <span>{{ item.spec }}</span>
                                </template>
                                <Icon name="el-icon-Goods" size="14" @mouseenter="item.visible = true" @mouseleave="item.visible = false" />
                            </el-tooltip>
                            {{ item.goods_name }}
                        </div>
                    </template>
                </el-table-column>
            </template>
            <!-- 订单状态 -->
            <template #order_status>
                <el-table-column :label="t('shop.order.order.status')" align="center" min-width="120">
                    <template #default="{ row }">
                        <el-tag v-if="row.status == orderStatusEnum.toShipped" class="tag-info" :type="getStatusType(row.status)">
                            <view v-if="row.delivery_status == orderStatusEnum.toReceive">{{ '部分发货' }}</view>
                            <view v-else> {{ t('shop.order.order.status ' + row.status) }} </view>
                        </el-tag>
                        <el-tag v-else-if="row.status == orderStatusEnum.applyCancel" class="tag-info" :type="getStatusType(row.status)">
                            {{ t('shop.order.order.status ' + row.status) }}
                        </el-tag>
                        <el-tag :type="getStatusType(row.status)" v-else> {{ t('shop.order.order.status ' + row.status) }}</el-tag>
                        <span style="margin-left: 5px; cursor: pointer">
                            <Icon name="fa fa-question-circle-o" @click="showStatusLog(row)" />
                        </span>
                    </template>
                </el-table-column>
            </template>
        </Table>

        <!-- 表单 -->
        <PopupForm />
        <!-- 订单状态日志弹窗 -->
        <StatusLogDialog v-if="baTable.table.extend!.showStatusLogDialog" />
        <!-- 详情弹窗 -->
        <DetailDialog v-if="baTable.table.extend!.showDetailDialog" />
        <!-- 发货弹窗 -->
        <DeliveryDialog v-if="baTable.table.extend!.showDeliveryDialog" />
        <!-- 取消订单弹窗 -->
        <CancelDialog v-if="baTable.table.extend!.showCancelDialog" />
        <!-- 导出弹窗 -->
        <ExportDialog v-if="baTable.table.extend!.showExportDialog" />
        <!-- 关闭弹窗 -->
        <CloselDialog v-if="baTable.table.extend!.showCloseDialog" />
    </div>
</template>

<script setup lang="ts">
import { ref, provide, onMounted, computed } from 'vue'
import baTableClass from '/@/utils/baTable'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import DetailDialog from './detailDialog.vue'
import DeliveryDialog from './deliveryDialog.vue'
import CancelDialog from './cancelDialog.vue'
import { useRoute } from 'vue-router'
import StatusLogDialog from './statusLogDialog.vue'
import { auth } from '/@/utils/common'
import {
    OrderStatusEnumType,
    orderStatusEnum,
    showDeliveryButton,
    showCancelButton,
    getStatusType,
    showCloseButton,
} from '/@/views/backend/shop/order/order/index'
import Icon from '/@/components/icon/index.vue'
import StatusWithBadge from '/@/components/shop/table/statusWithBadge.vue'
import ExportDialog from './exportDialog.vue'
import CloselDialog from './closelDialog.vue'
defineOptions({
    name: 'order/order',
})

const { t } = useI18n()
const tableRef = ref()
let optButtons: OptButton[] = []
//操作按钮
optButtons.push(
    //详情
    {
        render: 'tipButton',
        name: 'info',
        title: 'shop.order.order.detail',
        text: '',
        type: 'warning',
        icon: 'fa fa-search-plus icon',
        click(row) {
            baTable.table.extend!.showDetailDialog = true
            baTable.table.extend!.orderData = row
        },
    },
    //发货
    {
        render: 'tipButton',
        name: 'info',
        title: 'shop.order.order.delivery',
        text: '',
        type: 'success',
        icon: 'el-icon-Van',
        click(row) {
            baTable.table.extend!.showDeliveryDialog = true
            baTable.table.extend!.orderData = row
        },
        display: (row: TableRow) => {
            return showDeliveryButton(row)
        },
    },
    {
        render: 'tipButton',
        name: 'info',
        title: 'shop.order.order.refund',
        text: '',
        type: 'danger',
        icon: 'el-icon-Stamp',
        click(row) {
            baTable.table.extend!.showCancelDialog = true
            baTable.table.extend!.orderData = row
        },
        display: (row: TableRow) => {
            return showCancelButton(row)
        },
    },
    {
        render: 'tipButton',
        name: '',
        title: 'shop.order.order.close',
        text: '',
        type: 'danger',
        icon: 'fa fa-close',
        display: (row) => {
            return showCloseButton(row)
        },
        click: (row) => {
            baTable.table.extend!.showCloseDialog = true
            baTable.table.extend!.orderData = row
        },
    }
)

optButtons = optButtons.concat(defaultOptButtons(['delete']))

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/shop.order.Order/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            {
                label: t('shop.order.order.id'),
                prop: 'id',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: false,
                sortable: false,
            },
            {
                operator: false,
                render: 'slot',
                slotName: 'order_no_info',
            },
            {
                label: t('shop.order.order.status'),
                prop: 'status',
                align: 'center',
                show: false,
                comSearchRender: 'slot',
                comSearchSlotName: 'orderStatusSearch',
                comSearchColAttr: { xs: 24, sm: 24 },
            },
            {
                label: t('shop.order.order.order_no'),
                prop: 'order_no',
                align: 'center',
                operatorPlaceholder: t('shop.lang.Precise query'),
                operator: 'eq',
                sortable: false,
                minWidth: 220,
                showOverflowTooltip: true,
                show: false,
            },
            {
                label: t('shop.order.order.out_trade_no'),
                prop: 'out_trade_no',
                align: 'center',
                operatorPlaceholder: t('shop.lang.Precise query'),
                operator: 'eq',
                sortable: false,
                minWidth: 240,
                showOverflowTooltip: true,
                show: false,
            },
            {
                label: t('shop.order.order.goods_name'),
                prop: 'detail.goods_name',
                render: 'slot',
                align: 'left',
                slotName: 'goods_name',
                operator: false,
                operatorPlaceholder: t('Fuzzy query'),
                sortable: false,
            },
            {
                label: t('shop.order.order.user_nickname'),
                prop: 'user.nickname',
                align: 'center',
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
                showOverflowTooltip: true,
                minWidth: 120,
            },
            {
                label: t('shop.order.order.status'),
                render: 'slot',
                slotName: 'order_status',
                operator: false,
                prop: 'status',
                align: 'center',
                width: 100,
            },
            { label: t('shop.order.order.need_pay_price'), prop: 'pay_price', align: 'center', operator: 'RANGE', sortable: false, minWidth: 120 },
            { label: t('存储黄金g'), prop: 'gold_num', align: 'center', operator: 'RANGE', sortable: false, minWidth: 120 },

            {
                label: t('shop.order.order.pay_way'),
                prop: 'pay_way',
                render: 'tag',
                replaceValue: {
                    balance: t('shop.order.order.pay_way balance'),
                    wxpay: t('shop.order.order.pay_way wxpay'),
                    alipay: t('shop.order.order.pay_way alipay'),
                },
                align: 'center',
                operator: 'eq',
                sortable: false,
                comSearchRender: 'select',
                width: 100,
                custom: {
                    balance: 'warning',
                    wxpay: 'success',
                },
            },
            {
                label: t('shop.order.order.pay_status'),
                prop: 'pay_status',
                render: 'tag',
                replaceValue: {
                    1: t('shop.order.order.pay_status 1'),
                    2: t('shop.order.order.pay_status 2'),
                    3: t('shop.order.order.pay_status 3'),
                },
                align: 'center',
                operator: 'eq',
                sortable: false,
                comSearchRender: 'select',
                width: 100,
                custom: {
                    1: 'info',
                    2: 'success',
                    3: 'danger',
                },
            },
            {
                label: t('shop.order.order.create_time'),
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            {
                label: t('shop.order.order.pay_time'),
                prop: 'pay_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                sortable: 'custom',
                width: 160,
            },
            { label: t('Operate'), align: 'center', width: 150, render: 'buttons', buttons: optButtons, operator: false, fixed: 'right' },
        ],
        dblClickNotEditColumn: ['all'],
    },
    {
        defaultItems: {},
    },
    {
        getIndex: () => {
            if (!showAllStatus.value) {
                baTable.table.filter?.search?.push({ field: 'status', val: orderStatus, operator: 'eq' })
                baTable.comSearch.form.status = orderStatus
            }
        },
    },
    {
        getIndex: ({ res }) => {
            if (showAllStatus.value) {
                statusInfo.value = res.data.statusInfo
            }
        },
    }
)

provide('baTable', baTable)

type tabItem = {
    name: string
    value: string
    count: number
}
//订单状态信息
const statusInfo = ref<tabItem[]>([
    {
        name: '待付款',
        value: '1',
        count: 0,
    },
    {
        name: '待发货',
        value: '2',
        count: 0,
    },
    {
        name: '待收货',
        value: '3',
        count: 0,
    },
    {
        name: '待评价',
        value: '4',
        count: 0,
    },
    {
        name: '已完成',
        value: '5',
        count: 0,
    },
    {
        name: '已取消',
        value: '6',
        count: 0,
    },
    {
        name: '申请取消',
        value: '7',
        count: 0,
    },
])

baTable.table.showComSearch = true

const route = useRoute()

let orderStatus = 'all'
if (route.params.status && route.params.status !== 'all') {
    orderStatus = orderStatusEnum[route.params.status as keyof OrderStatusEnumType]
}
//权限控制
baTable.auth = (node: string) => {
    return auth({ name: '/admin/shop/order/order', subNodeName: '/admin/shop/order/order/' + node })
}
// 是否展示所有订单状态
const showAllStatus = computed(() => {
    return orderStatus === 'all'
})

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()

    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})

//订单状态日志弹窗
const showStatusLog = (row: TableRow) => {
    baTable.table.extend!.showStatusLogDialog = true
    baTable.table.extend!.orderStatusLog = row.status_log
    if (baTable.table.extend!.orderStatusLog.length > 0) {
        baTable.table.extend!.orderStatusLog[0].color = '#0bbd87'
    }
}
</script>

<style scoped lang="scss">
:deep(.el-badge__content.is-fixed) {
    top: -10px;
}

:deep(.cell) {
    // 最多两行，多余的显示省略
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    word-wrap: break-word;
    word-break: break-all;
}

@media screen and (min-width: 768px) {
    :deep(.table-com-search) {
        .status {
            .com-search-col-label {
                width: 8.3%;
            }
        }
    }
}
</style>
